package com.txcb.lib.base.utils;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author : Lambert
 * date   : 2020/10/28 3:38 PM
 */
public class Base64Util {

    /**
     * 将对象进行base64
     * @param object
     */
    public static String objectTo64Str( final Object object){

        String objBase64 = "";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            // 将对象的转为base64码
              objBase64 = new String(Base64.encodeBase64(baos
                    .toByteArray()));


            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return objBase64;
    }

    /**
     * 将SharePref中经过base64编码的对象读取出来
     *
     * @param objBase64
     * @return
     */
    public  static Object base64ToObject(  String objBase64) {
        // 对Base64格式的字符串进行解码
        byte[] base64Bytes = Base64.decodeBase64(objBase64.getBytes());
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);

        ObjectInputStream ois;
        Object obj = null;
        try {
            ois = new ObjectInputStream(bais);
            obj = (Object) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

}
